﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Caliburn.Micro;
using SharpTestsEx;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DomusDotNet.Sbm.Client.SL4.ViewModels;
using DomusDotNet.Sbm.Client.SL4.Services;
using DomusDotNet.Sbm.Client.SL4.WCFServices;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;
namespace DomusDotNet.Sbm.Client.SL4.Tests
{

    [TestClass]
    public class the_Container: TestBase
    {
        CompositionContainer container;
        public the_Container() {

            var catalog = AppBootstrapper.CreateCatalog();
            container = new CompositionContainer(catalog);
            AppBootstrapper.ConfigureContainer(container, catalog);
        }


     
        [TestMethod]
        public void should_resolve_all_VMs() {

            var vmTypes = typeof(AppBootstrapper).Assembly.GetExportedTypes()
                .Where(t => t.Name.EndsWith("ViewModel"))
                .Except(new[] { typeof(ShellViewModel) });

            foreach (var t in vmTypes) {
                TestPerRequest(t);
            }
        }

        [TestMethod]
        public void should_resolve_shell()
        {
            TestSingleton(typeof(IShell));
        }

        [TestMethod]
        public void should_resolve_services()
        {
            TestSingleton(typeof(ISecurityContext));
            TestSingleton(typeof(ISharedBookshelfService));
            //TestPerRequest(typeof(ISharedBookshelfService));
        }



        void TestSingleton(Type type) {

            var first = GetInstance(type);
                
            first.Should().Not.Be.Null();

            var second = GetInstance(type);

            second.Should().Be.SameInstanceAs(first);
        }

        void TestPerRequest(Type type)
        {
            var first = GetInstance(type);

            first.Should().Not.Be.Null();

            var second = GetInstance(type);

            second.Should().Not.Be.Null();
            second.Should().Not.Be.SameInstanceAs(first);
        }

        object GetInstance(Type type) {
            string contract = AttributedModelServices.GetContractName(type);
            var exports = container.GetExportedValues<object>(contract);

            if (exports.Count() > 0)
                return exports.First();

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }
    }


    
}

